"""Manage statuses and I/O for the tasks."""

import time
import threading

import task
import runner

class Manager(object):
    def __init__(self):
        self.tasks = []
        self.count = 0
        self.runner = runner.Runner()
        self.runner.set_manager(self)

    def start(self):
        """Start the runner and scanning threads."""
        self.runner.start()
        self.scan_unrun_event = threading.Event()
        self.scan_unrun_thread = threading.Thread(target=self.scan_unrun_tasks)
        self.scan_unrun_thread.start()

    def create_task(self, args):
        """Create a new task."""
        new_task = task.Task(self.count, args)
        self.tasks.append(new_task)
        self.count += 1
        self.scan_unrun_event.set()

    def poll_task(self, task_id):
        """Poll the status of the task."""
        pass

    def remove_task(self, task_id):
        """Remove an existing task."""
        pass

    def iterate_tasks(self):
        """Get an iterator of the task list."""
        return iter(self.tasks)

    def scan_unrun_tasks(self):
        # TODO: Check scan_unrun_event variable
        while True:
            self.scan_unrun_event.wait()
            time.sleep(1)
            # TODO: Break out at this point
            self.scan_unrun_event.clear()
            for t in self.tasks:
                if t.get_status() == task.UNRUN:
                    t.to_running()
            self.runner.wake_on_poller()
